package com.baoming.tool;

import java.io.IOException;
import java.io.StringReader; 
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
 
import com.baoming.domain.Properties;
import com.baoming.domain.SingupEnter; 
import com.baoming.util.ServiceTool;

public class XmlTool {
	  
	/**
	 * 生成XML文件 
	 * 生成格式
	 *  <property>
	 *  	<name></name>
	 *  	<value></value>
	 *  	<time></time>
	 *  </property>
	 * @param pageProps
	 * @return
	 */
	public static String createXml(List<Properties> pageProps){
		//创建xml文档 
		Document document=DocumentHelper.createDocument();
		//创建根元素
		Element rootElement=document.addElement("xml_body");
		for(Properties p : pageProps){
			//属性元素创建元素
			Element propertyEle=rootElement.addElement("property"); 
			//添加名字属性
			Element nameEle = propertyEle.addElement("name") ; 
			nameEle.setText(p.getName()) ; 
			//添加值属性
			Element valueEle = propertyEle.addElement("value") ; 
			valueEle.setText(p.getPageValue()) ; 
			//设定属性时间
			Element time = propertyEle.addElement("time") ; 
			time.setText(ServiceTool.getNowDate()) ; 
		}
		//生成String的方式 
		java.io.StringWriter out = new java.io.StringWriter(); 
		try {
			XMLWriter xw = new XMLWriter (out, new OutputFormat (" ", true, "utf-8"));
			xw.write(document);
		} catch (IOException e) { 
			e.printStackTrace();
		}finally{
			out.flush() ; 
			try {
				out.close() ;
			} catch (IOException e) { 
				e.printStackTrace();
			} 
		}
		String xmlstring = out.toString();
		return xmlstring;  
	}
	
	/**
	 * 返回集合
	 * @param xml
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<SingupEnter> createList(List<SingupEnter> enters){
		  
		for(SingupEnter enter : enters){
			Map<String , String> props = new HashMap<String , String>() ;
			String xml = enter.getXmlValue() ; 
			//创建解析器
			SAXReader saxReader = new SAXReader();  
			try {
				Document document = saxReader.read(new StringReader(xml));
				//得到根元素
				Element root = document.getRootElement();  
				for (Iterator<Element> iter = root.elementIterator("property"); iter.hasNext();) { 
					Element xmlElement = iter.next();
					String name = xmlElement.elementText("name");
					String value = xmlElement.elementText("value") ;   
					props.put(name, value) ;  
				}
			} catch (DocumentException e) { 
				e.printStackTrace();
			}  
			enter.setMap(props) ; 
		}
		return enters ; 
	} 
}
